﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Infrastructure.CustomException;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.EFCore.Extensions;
using QMERP.Infrastructure.Extensions;

namespace QMERP.Application.Services
{
    public class SupplierService : ISupplierService
    {
        private readonly IMapper _mapper;
        private readonly QMERPDbContext _db;
        public SupplierService(IMapper mapper, QMERPDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }
        /// <summary>
        /// 获取供应商列表基础数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<SupplierResponse>> GetBasicSuppliers()
        {
            var list = await _db.Supplier.ToListAsync();
            return _mapper.Map<List<SupplierResponse>>(list);
        }
        /// <summary>
        /// 供应商窗体
        /// </summary>
        /// <returns></returns>
        public async Task<PageResponse<SupplierResponse>> Query(PageRequest<SupplierRequest> request)
        {
            var response = new PageResponse<SupplierResponse>();

            var query = Where(request);

            var list = await query.Paging(request.PageIndex, request.PageSize).ToListAsync();
            var supplierResponse = _mapper.Map<List<SupplierResponse>>(list);
            response.TotalCount = await query.CountAsync();
            response.PageIndex = request.PageIndex;
            response.PageSize = request.PageSize;
            response.List = supplierResponse;
            return response;
        }
        /// <summary>
        /// 获取id的供应商详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SupplierResponse> Detail(long id)
        {
            var model = await _db.Supplier.FindByIdAsync(id);
            return _mapper.Map<SupplierResponse>(model);
        }
        /// <summary>
        /// 供应商保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(SupplierSaveRequest request)
        {
            if (await _db.Supplier.AnyAsync(x => x.Code.ToLower() == request.Code && x.Id != request.Id))
                throw new ApiException("供应商代码已存在!");
            if (await _db.Supplier.AnyAsync(x => x.Name.ToLower() == request.Name && x.Id != request.Id ))
                throw new ApiException("供应商名称已存在!");
            //if (await _db.Supplier.AnyAsync(x => x.ShortName.ToLower() == request.ShortName && x.Id != request.Id ))
            //    throw new ApiException("供应商简称已存在!");
            if (request.Id == null)
            {
                Supplier model = _mapper.Map<Supplier>(request);
                await _db.Supplier.AddAsync(model);
            }
            else
            {
                Supplier? model = await _db.Supplier.FindByIdAsync(request.Id.Value);
                if (model == null)
                    throw new ApiException("供应商不存在!");
                model.Code = request.Code;
                model.Name = request.Name;
                model.ShortName = request.ShortName;
                model.AreaCode = request.AreaCode;
                model.TradeCode = request.TradeCode;
                model.Address = request.Address;
                model.PostCode = request.PostCode;
                model.Taxpayer = request.Taxpayer;
                model.Bank = request.Bank;
                model.BankAccount = request.BankAccount;
                model.Fax = request.Fax;
                model.Email = request.Email;
                model.ContactPerson = request.ContactPerson;
                model.ContactType = request.ContactType;
                model.CreditGrade = request.CreditGrade;
                model.Priority = request.Priority;
                model.Sort = request.Sort;
            }
            await _db.SaveChangesAsync();
        }

        private IQueryable<Supplier> Where(PageRequest<SupplierRequest> request)
        {
            IQueryable<Supplier> query = _db.Supplier;
            if (!request.Query.Code.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Code.Contains(request.Query.Code!));
            }
            if (!request.Query.Name.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Name.Contains(request.Query.Name!));
            }
            return query.OrderByDescending(x => x.CreatedOn);
        }
    }
}
